import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {FetchService} from '../../core/net/fetch.service';
import {NzMessageService} from 'ng-zorro-antd';
import {ActivatedRoute, Router} from "@angular/router";
import {jsondata} from "./data4";
import * as _ from 'lodash';
declare var $: any;

@Component({
  selector: 'app-gooflow-detail',
  templateUrl: './gooflow-detail.component.html',
  styleUrls: ['./gooflow-detail.component.scss']
})
export class GooflowDetailComponent implements OnInit {
  editType;
  flowDetailData: any = {};
  flowName = '新建模板';
  flowId = '';
  flowVersion = '';
  relaForm = '';
  property = {
    width: 1200,
    height: 700,
    toolBtns: ["start round mix", "end round mix", "task"],
    haveHead: true,
    headLabel: true,
    headBtns: ["new", "open", "save", "undo", "redo", "reload"], // 如果haveHead=true，则定义HEAD区的按钮
    haveTool: true
  };
  remark = {
    cursor: "选择指针",
    direct: "结点连线",
    start: "入口结点",
    end: "结束结点",
    task: "任务结点"
  };
  flowTemp;
  flowchartdata;
  gooflowForm: FormGroup;
  focusItem;

  constructor(private fb: FormBuilder,
              private router: Router,
              private routerInfo: ActivatedRoute,
              private fetchService: FetchService,
              private message: NzMessageService) {
    this.flowId = this.routerInfo.snapshot.queryParams['id'];
    this.flowVersion = this.routerInfo.snapshot.queryParams['version'];
    this.editType = this.routerInfo.snapshot.queryParams['editType'];
    this.gooflowForm = this.fb.group({
      code: [null],
      name: [null],
      type: [null],
      model: [null],
      left: [null],
      top: [null],
      width: [null],
      height: [null],
      from: [null],
      to: [null],
      auditType: [null],
      auditVal: [null],
      allowBack: [null],
      formFields: [null]
    });
  }

  ngOnInit(): void {
    this.flowTemp = $.createGooFlow($("#flowTemp"), this.property);
    this.flowTemp.setNodeRemarks(this.remark);
    this.initFlowFunc();
    if (this.editType == 'view' || this.editType == 'edit') {
      this.checkDetail();
    }
  }

  initFlowFunc() {
    // 组件获得焦点事件
    this.flowTemp.onItemFocus = (id, type) => {
      this.gooflowForm.reset();
      this.focusItem = {
        id: id,
        type: type
      };
      this.gooflowForm.patchValue({code: id});
      this.gooflowForm.patchValue({model: type});
      let entity;
      if (type == "line") {
        entity = this.flowTemp.$lineData[id];
      } else if (type == "node") {
        entity = this.flowTemp.$nodeData[id];
      }
      console.log(entity);
      this.gooflowForm.patchValue(entity);
      return true;
    };

    // 组件失去焦点事件
    this.flowTemp.onItemBlur = (id, type) => {
      this.gooflowForm.reset();
      return true;
    };

    // 保存按钮事件
    this.flowTemp.onBtnSaveClick = () => {
      this.saveFlow();
    };

    // 组件删除事件(默认是取消的)
    this.flowTemp.onItemDel = (id, type) => {
      this.flowTemp.blurItem();	// 取消所选节点/连线被选定的状态。
      return true;
    };

    // 重置按钮事件
    this.flowTemp.onFreshClick = () => {
      this.flowTemp.clearData();
    };

    // 打印事件
    this.flowTemp.onPrintClick = () => {
      this.flowTemp.print(1);
    };

    // 导出图片事件
    const exportName = "事项流程图";
    this.flowTemp.onExportImgClick = () => {
      this.flowTemp.exportDiagram(exportName);
    };
  }

  checkDetail() {
    this.fetchService.get(`flow/flowTemp/${this.flowId}/${this.flowVersion}`).subscribe(res => {
      this.flowDetailData = res;
      this.flowName = this.flowDetailData.name;
      this.relaForm = this.flowDetailData.relaForm;
      this.flowTemp.setTitle(this.flowName);
      const data = this.formatResData(this.flowDetailData);
      this.flowTemp.loadData(data);
    });
  }

  editFlowItem(): void {
    const compId = this.gooflowForm.value.code;
    const compModel = this.gooflowForm.value.model;
    if (compId) {
      this.flowchartdata = this.flowTemp.exportData();
      if (compModel && compModel == "node") {
        $.each(this.flowchartdata.nodes, (key, node) => {
          if (key == compId) {
            this.flowchartdata.nodes[key] = _.defaultsDeep(this.gooflowForm.value, node);
          }
        });
      }
      if (compModel && compModel == "line") {
        $.each(this.flowchartdata.lines, (key, line) => {
          if (key == compId) {
            this.flowchartdata.lines[key] = _.defaultsDeep(this.gooflowForm.value, line);
          }
        });
      }
      const tempData = _.cloneDeep(this.flowchartdata);
      this.flowTemp.clearData();
      this.flowTemp.loadData(tempData);
      this.flowTemp.focusItem(this.focusItem.id, true);
    }
  }

  formatResData(data: any): any {
    const resJsonData = {
      title: data.name,
      nodes: {},
      lines: {}
    };
    data.flowNodeTempList.map(node => {
      resJsonData.nodes[node.code] = {
        name: node.name,
        left: node.left,
        top: node.top,
        type: node.type,
        width: 100,
        height: node.height,
        alt: true,
        auditType: node.auditType,
        auditVal: node.auditVal,
        allowBack: node.allowBack,
        formFields: node.formFields
      };
    });
    data.flowRouteTempList.map(line => {
      resJsonData.lines[line.code] = {
        name: line.name,
        type: line.type,
        from: line.from,
        to: line.to
      };
    });
    return resJsonData;
  }

  formatDataToSubmit(flowData: any): any {
    const submitData = {
      name: this.flowName,
      relaForm: this.relaForm,
      flowNodeTempList: [],
      flowRouteTempList: [],
      state: this.flowDetailData['state']
    };
    $.each(flowData.nodes, (key, node) => {
      const obj = node;
      obj.code = key;
      submitData.flowNodeTempList.push(obj);
    });
    $.each(flowData.lines, (key, line) => {
      const obj = line;
      obj.code = key;
      submitData.flowRouteTempList.push(obj);
    });
    return submitData;
  }

  saveFlow(): void {
    const nodeCount = this.flowTemp.$nodeCount; // 节点数（包含开始结束节点数）
    if (nodeCount > 0) {
      const flowchart = this.flowTemp.exportData();
      const submitData = this.formatDataToSubmit(flowchart);
      if (this.flowDetailData['flowId']) {
        submitData.flowId = this.flowDetailData['flowId'];
        this.fetchService.post<any>('flow/flowTemp/edit', submitData)
          .subscribe(res => {
            this.message.success('操作成功');
        });
      } else {
        this.fetchService.post<any>('flow/flowTemp/add', submitData).subscribe(res => {
          this.message.success('操作成功');
        });
      }
      console.log(submitData);
    } else {
      alert("请先绘制流程图");
    }
  }

  backToList() {
    this.router.navigate(['/gooflow/list']);
  }
}
